<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>

<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>

<%@ page import="org.apache.commons.fileupload.FileItem" %>


<%@ page import="java.io.*" %>

<%
 	//FileItem接口
	//DiskFileItemFactory实现类 implements FileItemFactory接口
    //ServletFileUpload文件上传的核心类
    
    request.setCharacterEncoding("UTF-8");
    //服务器保存的上传文件的路径
    String savePath = request.getServletContext().getRealPath("upload");
	
	out.println("savePath=" + savePath);
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if(isMultipart){
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		//将请求对象中的数据转换成为List<FileItem>，一个FileItem类型对象对应一个表单控件(<input type="text|password|checkbox|radio|file....")
		 List<FileItem>  itemList = upload.parseRequest(request);
		 for(FileItem item : itemList){
			 if(item.isFormField() == true) {//普通表单数据 例如：上传者 
				 String name = item.getFieldName();
			     if(name.equals("uploader")){
			    	 String author = item.getString("UTF-8");
			    	 out.println("上传者是：" + author);
			     }
			 }
			 else {//文件上传表单数据，例如：上传图片
				 String path = item.getName();//FF、Chrome struts2.png  //IE C:\\Users\\DANIU\\Desktop\\图片\\struts2.png
				 if(item.getSize() > 0){ //getSize()获得文件大小
					 File fullFile = new File(path);
				     String filename = fullFile.getName(); //获得真正的上传的文件名称  一定就干净的struts2.png
				     
				     item.write(new File(savePath,filename));//E:\\apache-tomcat-9.0.0.M22\\webapps\\news\\upload\\struts2.png
				     out.println("文件上传成功！");
				 }
			 }
		 }
	}
	
%>